//
//  MessageHelper.swift
//  PlayWithXMPP_Swift
//
//  Created by admin on 15/1/27.
//  Copyright (c) 2015年 com.zhongyan. All rights reserved.
//

import UIKit

class MessageHelper: NSObject, XMPPStreamDelegate {
   
    var receiveMsgArray:[ChatInfoModel] = []
    var sendMsgArray:[ChatInfoModel] = []
    var tableViewReloadClosure:TableViewReloadClosure?

    
    func xmppStreamDidConnect(sender: XMPPStream!) {
        println(__FUNCTION__, __LINE__);
        let password = UserInfoHelper.getPassword()
        AppDelegate.shareInstance().xmppStream!.authenticateWithPassword(password, error: nil)
    }
    
    func xmppStream(sender: XMPPStream!, didSendMessage message: XMPPMessage!) {
        println(__FUNCTION__, __LINE__);
    }
    
    func xmppStream(sender: XMPPStream!, didReceivePresence presence: XMPPPresence!) {
        println(__FUNCTION__, __LINE__);
    }
    func xmppStream(sender: XMPPStream!, didReceiveMessage message: XMPPMessage!) {
        println(__FUNCTION__, __LINE__);
        if message.isChatMessageWithBody() {
            let messageStr:NSString = message.elementForName("body").stringValue()
            let nameStr:NSString = message.attributeForName("from").stringValue()
            var chatInfoModel:ChatInfoModel = ChatInfoModel()
            chatInfoModel.message = messageStr
            chatInfoModel.name = nameStr
            self.receiveMsgArray.append(chatInfoModel)
            if (tableViewReloadClosure != nil) {
                tableViewReloadClosure!()
            }
        }
    }
    
    func xmppStream(sender: XMPPStream!, didNotAuthenticate error: DDXMLElement!) {
        
    }
    
    func xmppStreamDidAuthenticate(sender: XMPPStream!) {
        println(__FUNCTION__, __LINE__);
        let presence:XMPPPresence = XMPPPresence()
        AppDelegate.shareInstance().xmppStream?.sendElement(presence)
        
        
        
    }
    
}
